package org.fle4y.example.aio.sendfile;

import java.io.File;
import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;

import org.fle4y.common.utils.log.LogUtil;
import org.fle4y.framework.net.LogicHandler;
import org.fle4y.framework.net.Message;
import org.fle4y.framework.net.aio.AIOServer;
import org.fle4y.framework.net.aio.AIOSession;

/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-6-10<br>
 * 
 * @version : 1.0<br>
 *          mailto:flexie@foxmail.com<br>
 *          Description : 文件传输逻辑处理
 */
public class FileLogicHandler implements LogicHandler {
	private static final Logger log = LogUtil.getLogger(FileLogicHandler.class
			.getName());
	private AIOServer server;
	private AsynchronousSocketChannel channel;
	private FileChannel fc;

	public FileLogicHandler() {
		Properties props = new Properties();
		try {
			props.load(this.getClass().getResourceAsStream("file.ini"));
			File file = new File(props.getProperty("filebakpath"));
			fc = FileChannel.open(file.toPath(), StandardOpenOption.CREATE,
					StandardOpenOption.WRITE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void doLogic(AIOSession channel, LinkedBlockingQueue<Message> input,
			LinkedBlockingQueue<Message> output) {
		log.info("开始进行文件逻辑处理");
		try {
			Message msg = null;
			while ((msg = input.poll()) != null) {
				fc.write(msg.getContent());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void endCallBack() {
		try {
			fc.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public AsynchronousSocketChannel getChannel() {
		return channel;
	}

	public void setChannel(AsynchronousSocketChannel channel) {
		this.channel = channel;
	}

	public void setServer(AIOServer server) {
		this.server = server;
	}

	public AIOServer getServer() {
		return server;
	}

}
